package com.yingpai.fitness.dvp_2_0.main.activity.shop;

import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.donkingliang.labels.LabelsView;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.Utils;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.bean.ShopServiceCom;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.WXShareUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.CornersTransform;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.dvp_2_0.main.widget.MyBanner;
import com.yingpai.fitness.entity.ReadyOrderBean;
import com.yingpai.fitness.entity.ShopDetailBean;
import com.yingpai.fitness.entity.ShopDetailMcipBean;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;
import com.yingpai.fitness.entity.shop.detail.PhotoEventMessage;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import com.zzhoujay.richtext.RichText;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;


public class ShopDetailActivity extends CommonActivity {

    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.commDetailVp)
    MyBanner commDetailVp;
    @BindView(R.id.shopCommodityNameTv)
    TextView shopCommodityNameTv;
    @BindView(R.id.vipPriceTv)
    TextView vipPriceTv;
    @BindView(R.id.vip_price)
    TextView vipPrice;
    @BindView(R.id.commoditySaleTvNum)
    TextView commoditySaleTvNum;
    @BindView(R.id.textview1)
    TextView textview1;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.textview2)
    TextView textview2;
    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.commenttv)
    TextView commenttv;
    @BindView(R.id.head_photo)
    CircleImageView headPhoto;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.specs)
    TextView specs;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.shopInfomationWb)
    TextView shopInfomationWb;
    @BindView(R.id.scrollview)
    NestedScrollView scrollview;
    @BindView(R.id.postPrice)
    TextView postPrice;
    @BindView(R.id.comment_rl)
    RelativeLayout comment_rl;
    @BindView(R.id.comment_rl_count)
    RelativeLayout comment_rl_count;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout mFlowLayout;
    @BindView(R.id.discountVip)
    TextView mtv_discountvip;
    @BindView(R.id.servicepromise)
    RelativeLayout mlayout_servicepromise;
    private Dialog dialog;
    private RelativeLayout buySubtractIv;//减
    private RelativeLayout buyAddIv;//加
    private Long id;
    private XListView mciplistview;
    private QuickAdapter<ShopDetailBean.MapBean.PropertySetBean> mcipadapter;
    private Dialog share_dialog;
    private ShopDetailBean mShopDetailBean;
    private TokenBean tokenBean;
    private DecimalFormat df = new DecimalFormat("######.###");
    private LayoutInflater mInflater;
    private StringBuilder sb = new StringBuilder();
    @BindView(R.id.commentLine)
    View commentLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.shop_detail_activity);
    }

    @Override
    protected void initView() {
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        setTitle("商品详情");
        Drawable drawableLeft = getResources().getDrawable(
                R.mipmap.share);
        right_tv.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                null, null, null);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            id = Long.valueOf(bundle.getInt("id", -1));
        }

        final int startColor = ContextCompat.getColor(this, R.color.normal_status);
        final int endColor = ContextCompat.getColor(this, R.color.colorNavigation);

        scrollview.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int headHeight = commDetailVp.getHeight();
                int scrollDistance = Math.min(scrollY, headHeight);
                float fraction = (float) scrollDistance / (float) headHeight;

//                setToolbarStatusBarAlpha(evaluate(fraction, startColor, endColor),titleBar);
                setNavigationViewColor(evaluate(fraction, startColor, endColor));
            }
        });

        mInflater = LayoutInflater.from(this);
    }

    @Override
    protected void initData() {
        showDialog(this, null);
        HttpParams httpParams = new HttpParams();
        httpParams.put("id", id);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_DETAIL,
                httpParams, Url.SHOP_DETAIL, new Callback<ShopDetailBean>() {
                    @Override
                    public void onSuccess(ShopDetailBean shopDetailBean) {
                        dismissDialog();
                        if (Constant.REQUEST_SUCCESS.equals(shopDetailBean.getResult())) {
                            mShopDetailBean = shopDetailBean;

                            shopDetailBean.getMap().setMicpBeanList(GsonUtil.jsonToList(shopDetailBean.getMap().getMcipList(), ShopDetailMcipBean.class));

                            for (int i = 0; i < shopDetailBean.getMap().getMicpBeanList().size(); i++) {
                                List<ShopDetailMcipChildBean> list = GsonUtil.jsonToList(shopDetailBean.getMap().getMicpBeanList().get(i).getPropertyValue(), ShopDetailMcipChildBean.class);
                                Comparator comparator = Collections.reverseOrder();
                                Collections.sort(list, comparator);
                                shopDetailBean.getMap().getMicpBeanList().get(i).setProperty(list);
                            }

                            Comparator comparator = Collections.reverseOrder();
                            Collections.sort(shopDetailBean.getMap().getPropertySet(), comparator);

                            for (int j = 0; j < shopDetailBean.getMap().getPropertySet().size(); j++) {
                                List<String> list = new ArrayList<>();
                                for (int i = 0; i < shopDetailBean.getMap().getMicpBeanList().size(); i++) {
                                    if (!list.contains(shopDetailBean.getMap().getMicpBeanList().get(i).getProperty().get(j).getPropertyValue())) {
                                        list.add(shopDetailBean.getMap().getMicpBeanList().get(i).getProperty().get(j).getPropertyValue());
                                    }
                                }
                                shopDetailBean.getMap().getPropertySet().get(j).setList(list);
                            }

                            commDetailVp.setOnBannerListener(new OnBannerListener() {
                                @Override
                                public void OnBannerClick(int position) {
                                    EventBus.getDefault().postSticky(new PhotoEventMessage(position, Arrays.asList(mShopDetailBean.getMap().getMerchandise().getPhotoUrls().split(","))));
                                    startActivity(PhotoActivity.class);
                                }
                            });

                            commDetailVp.setImages(Arrays.asList(shopDetailBean.getMap().getMerchandise().getPhotoUrls().split(",")))
                                    .setBannerStyle(BannerConfig.NUM_INDICATOR)
                                    .setIndicatorGravity(BannerConfig.CENTER)
                                    .setImageLoader(new GlideImageLoader())
                                    .start();

                            shopCommodityNameTv.setText(shopDetailBean.getMap().getMerchandise().getMerchandiseName());
                            if (df.format(shopDetailBean.getMap().getMerchandise().getPostPrice() / 100).equals("0")) {
                                postPrice.setText("快递：包邮");
                            } else {
                                postPrice.setText("邮费：" + df.format(shopDetailBean.getMap().getMerchandise().getPostPrice() / 100) + "元");
                            }
                            commoditySaleTvNum.setText("自营"/* + shopDetailBean.getMap().getMerchandise().getSalesAmount()*/);

                            if (shopDetailBean.getMap().getPromotionList() != null && shopDetailBean.getMap().getPromotionList().size() != 0) {
                                textview1.setText(shopDetailBean.getMap().getPromotionList().get(0).getCategoryInfo().replace("$$", shopDetailBean.getMap().getPromotionList().get(0).getPromotionValue() + ""));
                                if (shopDetailBean.getMap().getPromotionList().size() > 1) {
                                    textview2.setText(shopDetailBean.getMap().getPromotionList().get(1).getCategoryInfo().replace("$$", shopDetailBean.getMap().getPromotionList().get(1).getPromotionValue() + ""));
                                } else {
                                    linearLayout2.setVisibility(View.GONE);
                                }
                            } else {
                                linearLayout1.setVisibility(View.GONE);
                                linearLayout2.setVisibility(View.GONE);
                            }

                            vipPrice.setText("￥" +df.format(shopDetailBean.getMap().getMicpBeanList().get(0).getMemberPrice() / 100) + "");
                            vipPriceTv.setText("原价￥" + df.format(shopDetailBean.getMap().getMicpBeanList().get(0).getCommonPrice() / 100));

                            if(shopDetailBean.getMap().getCommentsCount()>0){
                                comment_rl_count.setVisibility(View.VISIBLE);
                                commenttv.setText("评价" + shopDetailBean.getMap().getCommentsCount());
                            }else{
                                comment_rl_count.setVisibility(View.GONE);
                            }
                            if (shopDetailBean.getMap().getCommentsList() != null &&
                                    shopDetailBean.getMap().getCommentsList().size() != 0) {
                                comment_rl.setVisibility(View.VISIBLE);
                                Glide.with(ShopDetailActivity.this)
                                        .load(shopDetailBean.getMap().getCommentsList().get(0).getCustomerPhotoUrl())
                                        .centerCrop()
                                        .error(R.mipmap.icon_user_default)
                                        .into(headPhoto);
                                name.setText(shopDetailBean.getMap().getCommentsList().get(0).getCustomerName());
                                content.setText(shopDetailBean.getMap().getCommentsList().get(0).getComment());
//                        specs.setText(shopDetailBean.getMap().getCommentsList().get(0).getMcipValue());
                            } else {
                                comment_rl.setVisibility(View.GONE);
                                commentLine.setVisibility(View.GONE);
                            }

                            if(!TextUtils.isEmpty(shopDetailBean.getMap().getDiscountDesp())){
                                /*String disCount = "开通会员立享"+shopDetailBean.getMap().getDiscount()+"折";

                                SpannableStringBuilder builder = new SpannableStringBuilder(disCount);
                                ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.parseColor("#FFFF5656"));
                                builder.setSpan(redSpan,6,6+shopDetailBean.getMap().getDiscount().length(),
                                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);*/
                                mtv_discountvip.setText(shopDetailBean.getMap().getDiscountDesp());
                            }else{
                                mtv_discountvip.setVisibility(View.GONE);
                            }

                            if(null != shopDetailBean.getMap().getServiceCommitment()){
                                if(shopDetailBean.getMap().getServiceCommitment().size() > 0){
                                    mFlowLayout.setAdapter(new TagAdapter<ShopDetailBean.MapBean.ServiceCommitmentBean>
                                            (shopDetailBean.getMap().getServiceCommitment())
                                    {
                                        @Override
                                        public View getView(FlowLayout parent, int position,
                                                            ShopDetailBean.MapBean.ServiceCommitmentBean bean)
                                        {
                                            TextView tv = (TextView) mInflater.inflate(R.layout.flow_tv_layout, mFlowLayout, false);
                                            tv.setText(bean.getTitle());
                                            return tv;
                                        }
                                    });
                                    mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
                                    {
                                        @Override
                                        public boolean onTagClick(View view, int position, FlowLayout parent)
                                        {
                                            ejectFrame();
                                            return true;
                                        }
                                    });
                                    for (int i = 0; i < shopDetailBean.getMap().getServiceCommitment().size(); i++) {
                                        sb.append(shopDetailBean.getMap().getServiceCommitment().get(i).getId()).append(",");
                                    }
                                    sb.substring(0,sb.toString().length()-1);
                                }else{
                                    mlayout_servicepromise.setVisibility(View.GONE);
                                }
                            }else{
                                mlayout_servicepromise.setVisibility(View.GONE);
                            }




                            RichText.fromHtml(shopDetailBean.getMap().getMerchandiseDetail().getDetailInfo()).into(shopInfomationWb);

                        } else {
                            showToast(shopDetailBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        commDetailVp.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //停止
        commDetailVp.stopAutoPlay();
    }

    private void showShareDialog() {
        LinearLayout shop_detail_share_layout = (LinearLayout) View.inflate(this, R.layout.shop_detail_share_layout, null);
        share_dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();

        TextView title = shop_detail_share_layout.findViewById(R.id.title);
        title.setText(mShopDetailBean.getMap().getMerchandise().getMerchandiseName());

        TextView common_price = shop_detail_share_layout.findViewById(R.id.common_price);
        TextView member_price = shop_detail_share_layout.findViewById(R.id.member_price);
        member_price.setText(df.format(mShopDetailBean.getMap().getMicpBeanList().get(0).getMemberPrice() / 100) + "");
        common_price.setText("￥" + df.format(mShopDetailBean.getMap().getMicpBeanList().get(0).getCommonPrice() / 100));

        ImageView photo = shop_detail_share_layout.findViewById(R.id.photo);
        Glide.with(this)
                .load(mShopDetailBean.getMap().getMerchandise().getPhotoUrls().split(",")[0])
                .error(R.mipmap.default_small_bg)
                .into(photo);

        shop_detail_share_layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share_dialog.dismiss();
            }
        });

        shop_detail_share_layout.findViewById(R.id.share_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareUtil wxShareUtil = new WXShareUtil(ShopDetailActivity.this);
                wxShareUtil.registerWx();
                //防止取值失败
                try {
                    wxShareUtil.share(mShopDetailBean.getMap().getMerchandiseShareInfo().getUrl(),
                            mShopDetailBean.getMap().getMerchandiseShareInfo().getTitle(),
                            mShopDetailBean.getMap().getMerchandiseShareInfo().getDescription(),
                            mShopDetailBean.getMap().getMerchandiseShareInfo().getThumb(), wxShareUtil.SHARETOFRIEND);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        shop_detail_share_layout.findViewById(R.id.share_circle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareUtil wxShareUtil = new WXShareUtil(ShopDetailActivity.this);
                wxShareUtil.registerWx();
                try {
                    wxShareUtil.share(mShopDetailBean.getMap().getMerchandiseShareInfo().getUrl(),
                            mShopDetailBean.getMap().getMerchandiseShareInfo().getTitle(),
                            mShopDetailBean.getMap().getMerchandiseShareInfo().getDescription(),
                            mShopDetailBean.getMap().getMerchandiseShareInfo().getThumb(), wxShareUtil.SHARETOPYQ);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        share_dialog.show();
        share_dialog.setContentView(shop_detail_share_layout);
    }

    private void showBuyDialog() {
        View view = View.inflate(this, R.layout.bottom_buy_layout, null);
        dialog = new Dialog(this, R.style.ShopDialogStyle);
        dialog.setContentView(view);

        buySubtractIv = (RelativeLayout) view.findViewById(R.id.buySubtractIv);
        buyAddIv = (RelativeLayout) view.findViewById(R.id.buyAddIv);
        final TextView buyNumEt = (TextView) view.findViewById(R.id.buyNumEt);
        ScrollView dialog_scrollView = view.findViewById(R.id.scrollview);
        ImageView photo = view.findViewById(R.id.photo);
        Glide.with(this)
                .load(mShopDetailBean.getMap().getMerchandise().getPhotoUrls().split(",")[0])
                .transform(new CornersTransform(this, 20))
                .error(R.mipmap.default_small_bg)
                .into(photo);
        TextView common_price = view.findViewById(R.id.common_price);
        TextView member_price = view.findViewById(R.id.member_price);
        member_price.setText(df.format(mShopDetailBean.getMap().getMicpBeanList().get(0).getMemberPrice() / 100) + "");
        common_price.setText("原价：￥" + df.format(mShopDetailBean.getMap().getMicpBeanList().get(0).getCommonPrice() / 100));
        //加载参数
        mciplistview = view.findViewById(R.id.mciplistview);

        mcipadapter = new QuickAdapter<ShopDetailBean.MapBean.PropertySetBean>(this, R.layout.item_shop_mciplist_parent) {
            @Override
            protected void convert(BaseAdapterHelper helper, final ShopDetailBean.MapBean.PropertySetBean item) {
                helper.setText(R.id.title, item.getPropertyName() + ":");

                LabelsView labels = helper.getView(R.id.labels);

                labels.setOnLabelSelectChangeListener(new LabelsView.OnLabelSelectChangeListener() {
                    @Override
                    public void onLabelSelectChange(TextView textView, Object o, boolean b, int i) {
                        item.setIsAbandoned(b);
                        item.setPropertyValue(o + "");
                    }
                });

                labels.setLabels(item.getList());
            }
        };

        mciplistview.setAdapter(mcipadapter);
        mciplistview.setFocusable(false);

        mcipadapter.clear();
        mcipadapter.addAll(mShopDetailBean.getMap().getPropertySet());
        mcipadapter.notifyDataSetChanged();

        dialog_scrollView.scrollTo(0, 0);

        buySubtractIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.parseInt(buyNumEt.getText().toString()) - 1 >= 1) {
                    buyNumEt.setText(Integer.parseInt(buyNumEt.getText().toString()) - 1 + "");
                }
            }
        });
        buyAddIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buyNumEt.setText(Integer.parseInt(buyNumEt.getText().toString()) + 1 + "");
            }
        });

        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.cart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.isDoubleClick()) {
                    dialog.dismiss();
                    startActivity(CartActivity.class);
                }
            }
        });

        view.findViewById(R.id.NowBuyTv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < mcipadapter.getCount(); i++) {
                    if (!mcipadapter.getItem(i).isIsAbandoned()) {
                        showToast("请选择商品规格");
                        return;
                    }
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("propertyId", mcipadapter.getItem(i).getId());
                        jsonObject.put("propertyValue", mcipadapter.getItem(i).getPropertyValue());
                        jsonArray.put(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                Logger.e(jsonArray.toString());

                showDialog(ShopDetailActivity.this, null);
                HttpParams httpParams = new HttpParams();
                httpParams.put("customerId", tokenBean.getId());
                httpParams.put("source", Constant.NUM_1);
                httpParams.put("merchandiseId", id);
                httpParams.put("merchandiseJson", jsonArray.toString());
                httpParams.put("purchaseAmount", Integer.parseInt(buyNumEt.getText().toString()));
                httpParams.put("shoppingCartIds", "");
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.ORDER_DETAIL, httpParams, Url.ORDER_DETAIL, new Callback<ReadyOrderBean>() {
                    @Override
                    public void onSuccess(ReadyOrderBean readyOrderBean) {
                        if (readyOrderBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("source", Constant.NUM_1);
                            bundle.putString("merchandiseId", id+"");
                            bundle.putString("merchandiseJson", jsonArray.toString());
                            bundle.putInt("purchaseAmount", Integer.parseInt(buyNumEt.getText().toString()));
                            startActivity(PurchaseOrderActivity.class, bundle);
                            dialog.dismiss();
                        } else {
                            showToast(readyOrderBean.getMsg());
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });

            }
        });
        //加入购物车
        view.findViewById(R.id.add_shop_cart_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(context, null);
                //防止连点
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < mcipadapter.getCount(); i++) {
                    if (!mcipadapter.getItem(i).isIsAbandoned()) {
                        showToast("请选择商品规格");
                        return;
                    }
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("propertyId", mcipadapter.getItem(i).getId());
                        jsonObject.put("propertyValue", mcipadapter.getItem(i).getPropertyValue());
                        jsonArray.put(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Logger.e(jsonArray.toString());
                HttpParams httpParams = new HttpParams();
                httpParams.put("customerId", tokenBean.getId());
                httpParams.put("merchandiseId", id);
                httpParams.put("mcipJson", jsonArray.toString());
                httpParams.put("quantity", Integer.parseInt(buyNumEt.getText().toString()));
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.ADD_SHOPPING_TO_CART, httpParams, Url.ADD_SHOPPING_TO_CART, new Callback<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse baseResponse) {
                        dismissDialog();
                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            dialog.dismiss();
                            startActivity(CartActivity.class);
                        } else {
                            showToast(baseResponse.getMsg());
                        }
                    }
                });
            }
        });


        Window dialogWindow = dialog.getWindow();
        WindowManager m = dialogWindow.getWindowManager();
        Display d = m.getDefaultDisplay();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        lp.height = (int) d.getHeight() / 3 * 2;
        lp.width = d.getWidth();
        // 设置显示位置
        dialog.onWindowAttributesChanged(lp);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();
    }

    @Override
    @OnClick({R.id.select_spec, R.id.all_comment, R.id.cart, R.id.add_shop_cart_tv, R.id.NowBuyTv, R.id.right_tv,
            R.id.servicepromise})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.servicepromise://服务承诺
                ejectFrame();
                break;
            case R.id.select_spec:
                showBuyDialog();
                break;
            case R.id.all_comment:
                Bundle bundle = new Bundle();
                bundle.putInt("merchandiseId", mShopDetailBean.getMap().getMerchandise().getId());
                startActivity(AllCommentActivity.class, bundle);
                break;
            case R.id.cart:
                startActivity(CartActivity.class);
                break;
            case R.id.add_shop_cart_tv:
                showBuyDialog();
                break;
            case R.id.NowBuyTv:
                showBuyDialog();
                break;
            case R.id.right_tv:
                showShareDialog();
                break;
        }
    }

    /**
     * 弹出框
     */
    private QuickAdapter<ShopServiceCom.DataBean> adapter;
    private void ejectFrame() {
        showDialog(this,"");
        HashMap<String,Object> httpParams = new HashMap<>();
        httpParams.put("ids",sb.toString());
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.OBTAINSERVICECOM,
                httpParams, Url.OBTAINSERVICECOM, new Callback<ShopServiceCom>() {
                    @Override
                    public void onSuccess(ShopServiceCom shopDetailBean) {
                        dismissDialog();
                        if(shopDetailBean.getCode().equals("0")){
                            DialogUtil.getInstance().showBottomDialog(ShopDetailActivity.this,
                                    R.layout.dialog_service_com);
                            LinearLayout zoneLayout = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
                            ListView listView = zoneLayout.findViewById(R.id.service_lv);
                            adapter = new QuickAdapter<ShopServiceCom.DataBean>(context,R.layout.item_service) {
                                @Override
                                protected void convert(BaseAdapterHelper helper, ShopServiceCom.DataBean item) {
                                    helper.setText(R.id.service_title,item.getTitle());
                                    helper.setText(R.id.service_content,item.getDescribe());
                                }
                            };
                            listView.setAdapter(adapter);
                            adapter.clear();
                            adapter.addAll(shopDetailBean.getData());
                            zoneLayout.findViewById(R.id.ikown).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.getInstance().dialog_bottom.dismiss();
                                }
                            });
                        }else{
                            showToast(shopDetailBean.getMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
    }
}
